// TestServer.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Client.h"
#include "DBServer.h"
#include "msgDBServer.h"
#include <string> 




xgc_void CDBServer::StartServer( xgc_lpcstr address, xgc_uint16 port, xgc_uint16 test_invent, xgc_uint16 timeout )
{
	//m_conn = new Conn("host=127.0.0.1 dbname=test user=postgres password=123456 port=5432 connect_timeout=5"); 
	ConnManager::GetInstance();

	net::IMessageQueue **mQueue = GetMessageQueue();
	mServer = net::StartServer( address, port, mQueue, test_invent, timeout, net::ProtocalDefault, 10 );

	__super::Start();
}

xgc_void CDBServer::StopServer()
{
	net::CloseServer( mServer );
	__super::Stop();
}

xgc_void CDBServer::RegisteMessage()
{
	RegistFunction( LS2DB_DB_MESSAGE_TYPE, LS2DB_LOGIN_REQUEST , bind( &CDBServer::CheckUserInfo, this, _1, _2, _3, _4 ) );
}

xgc_lpvoid CDBServer::OnAccept( net::network_t h, xgc_long_ptr from )
{
	return reinterpret_cast< xgc_lpvoid >( new CClient );
}

xgc_void CDBServer::OnClose( xgc_lpvoid userdata )
{
	delete reinterpret_cast< CClient* >( userdata );
}

//////////////////////////////////////////////////////////////////////////
xgc_void CDBServer::CheckUserInfo( net::network_t h, xgc_lpvoid u, const unsigned char* data, size_t size )
{
	msgDBCheckRequest request;

	Read( request,data,size );

	string name(request.username);
	string pawd(request.password);
	xgc_uint32 uuid = request.uuid;

	//string sql = "SELECT * from role where name = '" + name +"'";
	string sql = "SELECT role_query('"+ 
					name+ 
					"')";
	
	map_result res; 
	int tag;
	string password;
	ConnManager *conn_manager = ConnManager::GetInstance();
	//tag = conn_manager->GetConnection()->fetch(const_cast<char*>(sql.c_str()),res); 

	tag = conn_manager->GetConnection()->fetch_process(const_cast<char*>(sql.c_str()),res); 
	if (tag == 0)
	{
		map_result::iterator it = res.begin(); 
		for( ; it!=res.end(); ++it ) 
		{ 
			std::cout <<"ROW:"<< it->first << std::endl; 
			map<string,string>::iterator itField = it->second.begin(); 
			for( ; itField!=it->second.end(); ++itField ) 
			{ 
				password = itField->second;
			} 
		}
	}

	msgDBCheckResponse rpn;
	rpn.username = name.c_str();
	rpn.password = password.c_str();
	rpn.uuid = uuid;
	rpn.oid = request.oid;

	if (password == pawd)
	{
		rpn.result = TRUE;
	}
	else
	{
		rpn.result = false;
	}
	Send( h, rpn, 1024 );
}